package two_shang.otherTest.ThreadPackage;

import java.util.concurrent.locks.ReentrantLock;

public class BuyTiecktTest {
    public static void main(String[] args) {
        BuyT station = new BuyT();
        new Thread(station, "黄牛党").start();
        new Thread(station, "我").start();
        new Thread(station, "其他人").start();

    }
}

class BuyT implements Runnable {
    private int ticketNumb = 10;
    private boolean flag = true;
    private final ReentrantLock lock = new ReentrantLock();

    @Override
    public void run() {
        while (flag) {
            try {
                lock.lock();
                if (ticketNumb > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    System.out.println(Thread.currentThread().getName() + "获得了第" + ticketNumb-- + "张票");
                } else
                    flag = false;
            } finally {
                //    解锁
                lock.unlock();
            }
        }
    }
}
  /*  private synchronized void buy() throws InterruptedException {
//判断是否有票(没有票时)
        if (ticketNumb <= 0) {
            flag = false;
            System.out.println("没票了");
            return;
        }
//模拟延时
        Thread.sleep(1000);
//有票时
        System.out.println(Thread.currentThread().getName() + "获得了第" + ticketNumb-- + "张票");
    }*/

